package com.beidu.lottery.call.common;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息传输过滤器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class UserTransmitFilter extends OncePerRequestFilter {

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
        String userId = httpServletRequest.getHeader("userId");
        String tenant = httpServletRequest.getHeader("tenant");
        UserInfoDTO userInfoDTO = new UserInfoDTO(userId, tenant);
        BaseContextHandler.setUser(userInfoDTO);
        log.info("用户信息传入过滤器放入上下文=>{}", userInfoDTO);
        try {
            filterChain.doFilter(httpServletRequest, servletResponse);
        } finally {
            BaseContextHandler.removeUser();
        }
    }
}